package com.infoland.afanmall.model.order.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.activity.BaseCompatActivity;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.DecimalKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.address.activity.AddressAllActivity;
import com.infoland.afanmall.model.address.entity.AddressEntity;
import com.infoland.afanmall.model.order.adapter.OrderDownCartAdapter;
import com.infoland.afanmall.model.order.dialog.PayDialogBy;
import com.infoland.afanmall.model.order.entity.OrderByResponse;
import com.infoland.afanmall.model.order.entity.OrderCartByResponse;
import com.wang.avi.AVLoadingIndicatorView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 从购物车
 * 下单界面
 */
public class OrderDownActivity extends BaseCompatActivity {
    /***----------------->   公用下单参数  <-----------------***/
    private String now_type;   //当前下单类型

    /***----------------->   直接购买的下单控件  <-----------------***/
    @BindView(R.id.img)
    AppCompatImageView img;
    @BindView(R.id.txt_content)
    AppCompatTextView txtContent;
    @BindView(R.id.txt_gui_ge)
    AppCompatTextView txtGuiGe;
    @BindView(R.id.txt_price)
    AppCompatTextView txtPrice;
    @BindView(R.id.txt_count)
    AppCompatTextView txtCount;
    @BindView(R.id.order_down_item)
    LinearLayoutCompat orderDownItem;

    /***----------------->   直接购买的下单参数  <-----------------***/
    private String now_name;   //当前商品名子
    private Double now_price;   //当前商品价格
    private Double now_origin_price;   //原价
    private String now_gui_ge;    //当前规格
    private int now_price_id = -1;    //当前规格id
    private String now_gui_ge_name;    //当前规格名称
    private Object now_good_id;    //当前商品id
    private int now_count;    //当前选中数量
    private int now_count_max;    //可选最大量
    private int now_count_min;    //最小量
    private BigDecimal allPrice;    //最小量
    private String now_img_url;//

    /***----------------->   从购物车下单参数 <-----------------***/
    private int now_address_id = -1; //当前是否有地址
    public static int activityCode = 151;//当前activity的返回code
    private ArrayList<Integer> goodPriceIds;//所有商品id
    private Map<String, Integer> goodCountMap;//对应商品的购买数量
    private ArrayList<Integer> ids;//购物车数据id
    private String cartIds; //购物车数据id 转换之后的数据
    private int number = 0;

    /***----------------->   从购物车下单控件  <-----------------***/
    OrderDownCartAdapter orderDownCartAdapter;
    @BindView(R.id.address_yes_name)
    AppCompatTextView addressYesName;
    @BindView(R.id.address_yes_phone)
    AppCompatTextView addressYesPhone;
    @BindView(R.id.address_yes_moren)
    AppCompatTextView addressYesMoren;
    @BindView(R.id.address_yes_biao_qian)
    AppCompatTextView addressYesBiaoQian;
    @BindView(R.id.address_yes_address)
    AppCompatTextView addressYesAddress;
    @BindView(R.id.address_yes_click_content)
    LinearLayout addressYesClickContent;
    @BindView(R.id.address_yes)
    LinearLayoutCompat addressYes;
    @BindView(R.id.address_no_click_content)
    AppCompatTextView addressNoClickContent;
    @BindView(R.id.address_no)
    LinearLayoutCompat addressNo;
    @BindView(R.id.order_down_recycle)
    RecyclerView orderDownRecycle;
    @BindView(R.id.order_down_count)
    TextView orderDownCount;
    @BindView(R.id.order_down_price1)
    TextView orderDownPrice1;
    @BindView(R.id.order_down_youfei)
    TextView orderDownYoufei;
    @BindView(R.id.cart_back)
    LinearLayout cartBack;
    @BindView(R.id.cart_edit)
    TextView cartEdit;
    @BindView(R.id.title_layout)
    LinearLayout orderToolBar;
    @BindView(R.id.order_down_price2)
    TextView orderDownPrice2;
    @BindView(R.id.order_ti_jiao)
    Button orderTiJiao;
    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView aviPt;

    @Override
    public int setLayout() {
        return R.layout.order_cart_activity;
    }

    /***Main**/
    @Override
    public void initData() {
        getDefaultAddress();
        getBundlePara();
    }

    /*** 获取默认地址信息**/
    private void getDefaultAddress() {
        if (UserKit.isLogin()) {
            JSONObject para = new JSONObject();
            new OkHttpKit().send(
                    response200 -> {
                        if (response200.equals("{}")) {
                            now_address_id = -1;
                            addressYes.setVisibility(View.GONE);
                            addressNo.setVisibility(View.VISIBLE);
                        } else {
                            AddressEntity addressEntity = JSONObject.parseObject(response200, AddressEntity.class);
                            LogKit.E("   defaultEntity--->", "  " + response200);
                            addressNo.setVisibility(View.GONE);
                            addressYes.setVisibility(View.VISIBLE);
                            updateUIAddress(addressEntity);
                        }
                    },
                    error401 -> {
                        ToastUtils.showShort("登录失效请重新登录");
                        now_address_id = -1;
                        finish();
                    },
                    error -> {
                        ToastUtils.showShort("登录失效请重新登录");
                        now_address_id = -1;
                        finish();
                    }
            ).post(CONST.USER_DEFAULT_ADDRESS + UserKit.getAccessToken(), para, this);
        } else {
            ToastUtils.showShort("请登录后使用");
            finish();
        }
    }

    /*** 获取Bundle参数**/
    private void getBundlePara() {
        if (bundle != null) {
            now_type = bundle.getString("now_type");
            if (CONST.ORDER_TYPE_NOW_BY.equals(now_type)) {
                orderDownItem.setVisibility(View.VISIBLE);
                orderDownRecycle.setVisibility(View.GONE);
                getParaNowBy();
            } else if (CONST.ORDER_TYPE_CART.equals(now_type)) {
                orderDownItem.setVisibility(View.GONE);
                orderDownRecycle.setVisibility(View.VISIBLE);
                getParaCart();
            } else {
                orderDownItem.setVisibility(View.GONE);
                orderDownRecycle.setVisibility(View.GONE);
                ToastUtils.showShort("下单数据异常，请重新下单");
                finish();
            }
        } else {
            orderDownItem.setVisibility(View.GONE);
            orderDownRecycle.setVisibility(View.GONE);
            ToastUtils.showShort("下单数据异常，请重新下单");
            finish();
        }
    }

    /***获取 立即购买 传递过来的下单 参数*/
    private void getParaNowBy() {
        LogKit.E("  bundle ", "  " + bundle);
        if (bundle != null) {
            now_name = bundle.getString("now_name");
            now_price = bundle.getDouble("now_price");
            now_origin_price = bundle.getDouble("now_origin_price");
            now_gui_ge = bundle.getString("now_gui_ge");
            now_gui_ge_name = bundle.getString("now_gui_ge_name");
            now_good_id = bundle.get("now_good_id");
            now_count = bundle.getInt("now_count");
            now_count_max = bundle.getInt("now_count_max");
            now_count_min = bundle.getInt("now_count_min");
            now_price_id = bundle.getInt("now_price_id");
            now_img_url = bundle.getString("now_img_url");
            showData();
        } else {
            ToastUtils.showShort("下单数据异常，请重新下单");
            finish();
        }
    }

    /***展示订单商品信息 --立即购买 */
    private void showData() {
        ToolsKit.setImgActivity(OrderDownActivity.this, now_img_url, img);
        txtContent.setText(now_name + "");
        txtGuiGe.setText(now_gui_ge_name + "");
        txtPrice.setText("￥" + now_price + "");
        txtCount.setText("X" + now_count + "");
        allPrice = DecimalKit.mul(now_count, now_price);
        orderDownCount.setText("" + now_count + "");
        orderDownPrice1.setText("￥" + allPrice + "");
        orderDownPrice2.setText("￥" + allPrice + "");
    }

    /***获取 购物车 传递过来的下单 参数*/
    private void getParaCart() {
        if (bundle != null) {
            StringBuilder stringBuilder = new StringBuilder();
            ids = bundle.getIntegerArrayList("ids");
            for (int id : ids) {
                stringBuilder.append(id + ",");
            }
            cartIds = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
            showByCartGoods(cartIds);
        } else {
            ToastUtils.showShort("下单数据异常，请重新下单");
            finish();
        }

    }

    /*** 展示订单商品信息-- 购物车**/
    private void showByCartGoods(String cartIds) {
        if (bundle != null) {
            JSONObject para = new JSONObject();
            para.put("cartIds", cartIds);

            new OkHttpKit().send(
                    response200 -> {
                        JSONArray objects = JSONArray.parseArray(response200);
                        if (objects.size() > 0) {
                            OrderCartByResponse orderCartByResponse = JSONObject.parseObject(objects.get(0).toString(), OrderCartByResponse.class);
                            List<OrderCartByResponse.CartListBean> cartList = orderCartByResponse.getCartList();
                            setAdapter(cartList);
                            setPrice(cartList);
                        }
                    },
                    error401 -> {
                        LogKit.E("success401 ---->   ", "  " + error401);
                    },
                    error -> {
                        LogKit.E("error ---->   ", "  " + error);
                    }
            ).post(CONST.ORDER_GET_GOOD_LIST_BY_CART + UserKit.getAccessToken(), para, this);
        } else {
            ToastUtils.showShort("数据异常，请重新下单");
            finish();
        }
    }

    /*** 设置主界面总价格**/
    private void setPrice(List<OrderCartByResponse.CartListBean> cartList) {
        BigDecimal bigDecimal = DecimalKit.getDecimal(0.00);
        int count = 0;
        for (OrderCartByResponse.CartListBean bean : cartList) {
            count += bean.getGoods_count();
            BigDecimal mul = DecimalKit.mul(bean.getGoods_count(), bean.getGoods_price());
            bigDecimal = DecimalKit.add(bigDecimal, mul);
        }
        orderDownPrice2.setText(("￥" + bigDecimal));
        orderDownCount.setText((count + ""));
        orderDownPrice1.setText(("￥" + bigDecimal));
        orderDownYoufei.setText("免邮");

    }

    /*** 设置适配器 -- 购物车**/
    private void setAdapter(List<OrderCartByResponse.CartListBean> cartList) {
        orderDownCartAdapter = new OrderDownCartAdapter(R.layout.order_down_item, cartList);
        orderDownRecycle.setLayoutManager(new LinearLayoutManager(this));
        orderDownRecycle.setAdapter(orderDownCartAdapter);
    }

    /*** 下单--从立即购买**/
    private void submitOrderNowBy() {
        JSONObject para = new JSONObject();
        para.put("goodsCount", now_count);//商品数量
        para.put("goodsId", now_good_id);//商品id
        para.put("goodsPriceId", now_price_id);//商品规格id
        para.put("addressId", now_address_id);//地址id
        para.put("type", 1);//1 APP   0 微信

        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("   submitOrderNowBy---> ", "  " + response200);
                    OrderByResponse orderNowByResponse = JSONObject.parseObject(response200, OrderByResponse.class);
                    if (orderNowByResponse.isSuccess()) {
                        LogKit.E(" 下单--->  ", "  完成");
                        openPay(orderNowByResponse.getObject());
                    } else {
                        now_address_id = -1;
                        ToastUtils.showShort(orderNowByResponse.getMessage());
                    }
                },
                error401 -> {
                    now_address_id = -1;
                    ToastUtils.showShort("登录失效请重新登录");
                    finish();
                },
                error -> {
                    now_address_id = -1;
                    ToastUtils.showShort("登录失效请重新登录");
                    finish();
                }
        ).post(CONST.ORDER_SUBMIT_NOW_BY + UserKit.getAccessToken(), para, this);
    }

    /*** 下单--从购物车**/
    private void submitOrderByCart() {
        if (now_address_id != -1) {
            JSONObject para = new JSONObject();
            para.put("addressId", now_address_id);//地址id
            para.put("cartIdRemarkList", getOrderCartPara());//JSON数组，见示例
            para.put("type", 1);//来源 1：APP 0：微信

            new OkHttpKit().send(
                    response200 -> {
                        LogKit.E("   submitOrderByCart---> ", "  " + response200);
                        OrderByResponse orderByResponse = JSONObject.parseObject(response200, OrderByResponse.class);
                        if (orderByResponse.isSuccess()) {
                            LogKit.E(" 下单--->  ", "  完成");
                            openPay(orderByResponse.getObject());
                        } else {
                            now_address_id = -1;
                            ToastUtils.showShort(orderByResponse.getMessage());
                        }

                        LogKit.E("response200 ---->   ", "  " + response200);
                    },
                    error401 -> {
                        now_address_id = -1;
                        ToastUtils.showShort("登录失效请重新登录");
                        finish();
                    },
                    error -> {
                        now_address_id = -1;
                        ToastUtils.showShort("登录失效请重新登录");
                        finish();
                    }
            ).post(CONST.ORDER_SUBMIT_CART + UserKit.getAccessToken(), para, this);
        } else {
            ToastUtils.showShort("数据异常，请重新购买");
        }

    }

    /*** 购物车下单参数**/
    private JSONArray getOrderCartPara() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
//        {
//            "subCartId": "70,71",
//                "remark": "订单备注"
//        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int id : ids) {
            stringBuilder.append(id + ",");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        jsonObject = new JSONObject();
        jsonObject.put("subCartId", stringBuilder.toString());
        jsonObject.put("remark", "");
        jsonArray.add(jsonObject);
        return jsonArray;
//        {
//            "subCartId":"购物车数据id",
//                "remark":"订单备注"
//        },

    }

    /*** 检查地址**/
    private void checkAddress() {
        if (now_address_id != -1) {
            if (CONST.ORDER_TYPE_NOW_BY.equals(now_type)) {
                submitOrderNowBy();
            } else if (CONST.ORDER_TYPE_CART.equals(now_type)) {
                submitOrderByCart();
            } else {
                ToastUtils.showShort("下单数据异常，请重新下单");
                finish();
            }
        } else {
            ToastUtils.showShort("请先选择收货地址");
        }

    }

    /*** 下单成功 打开支付界面**/
    private void openPay(OrderByResponse.ObjectBean object) {
        PayDialogBy payDialogNowBy = new PayDialogBy(object, this, now_type);
        payDialogNowBy.setShowBottom(true);
        payDialogNowBy.setOutCancel(false);
//        payDialogNowBy.setCancelable(false);
        payDialogNowBy.show(getSupportFragmentManager());
    }


    /*** 获取ID地址**/
    private void getAddressById(int addressId) {
        JSONObject para = new JSONObject();
        para.put("id", addressId);
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("   getAddressById---> ", "  " + response200);
                    AddressEntity addressEntity = JSONObject.parseObject(response200, AddressEntity.class);
                    addressNo.setVisibility(View.GONE);
                    addressYes.setVisibility(View.VISIBLE);
                    updateUIAddress(addressEntity);
                },
                error401 -> {
                    ToastUtils.showShort("登录失效请重新登录");
                    finish();
                },
                error -> {
                    ToastUtils.showShort("登录失效请重新登录");
                    finish();
                }
        ).post(CONST.SELECT_ADDRESS_BY_ID + UserKit.getAccessToken(), para, this);

    }

    /*** 更新地址数据**/
    private void updateUIAddress(AddressEntity addressEntity) {
        now_address_id = addressEntity.getId();
        addressYesBiaoQian.setText("没有");
        addressYesName.setText(addressEntity.getReceiver_name());
        /*** 设置是否默认**/
        if (addressEntity.getDefault_flag() == 1) {
            //            默认
            addressYesMoren.setVisibility(View.VISIBLE);
            addressYesMoren.setText("默认");
        } else {
            addressYesMoren.setVisibility(View.GONE);
            addressYesMoren.setText("");
        }
        addressYesPhone.setText(ToolsKit.phoneXing(addressEntity.getReceiver_tel()));
        addressYesAddress.setText((addressEntity.getProvince_city_area() + addressEntity.getUser_address() + ""));

    }


    /*** 支付失败回调**/
    public void payErro(String s) {

    }

    /*** 支付成功回调**/
    public void paySuccess(String s) {

    }

    /*** 支付成功回调**/
    public void back(String s) {

    }

    @OnClick({
            R.id.address_yes_address, R.id.address_no, R.id.address_yes,
            R.id.cart_back, R.id.order_ti_jiao, R.id.address_yes_click_content,
            R.id.address_no_click_content, R.id.address_yes_name, R.id.address_yes_phone,
            R.id.address_yes_moren, R.id.address_yes_biao_qian
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cart_back:
                finish();
                break;
            /*** 提交订单**/
            case R.id.order_ti_jiao:
                checkAddress();
                break;
            /*** 选择收获地址 （此时有地址）**/
            case R.id.address_yes:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
            /*** 选择收获地址（此时没有地址）**/
            case R.id.address_no:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
            case R.id.address_yes_click_content:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
            case R.id.address_no_click_content:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
            case R.id.address_yes_address:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
            case R.id.address_yes_name:
                ToolsKit.goResult(this, AddressAllActivity.class, null, activityCode);
                break;
        }
    }

    @Override
    public void init() {
        ButterKnife.bind(this);
    }

    /*** 接收返回的ID**/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == activityCode) {
            Bundle extras = data.getExtras();
            int addressId = extras.getInt("addressId");
            LogKit.E(" resultCode  ", "  " + resultCode);
            LogKit.E(" requestCode  ", "  " + requestCode);
            LogKit.E(" addressId  ", "  " + addressId);
            getAddressById(addressId);
        }
    }

    @Override
    protected void onDestroy() {
        ToolsKit.deleteOKHttp(this);
        super.onDestroy();
    }
}


//    /***发送请求，返回价格和库存**/
//    private void getPrice(StringBuilder id_para, int id) {
//        String url = CONST.HTTP + CONST.GUI_GE_PRICE;
//        JSONObject para = new JSONObject();
//        para.put("id", id);
//        para.put("goodsSpecJson", id_para.toString());
//        LogKit.E("goodsSpecJson   ", "  " + para.toJSONString());
//        new HttpUtils(new HttpUtils.HttpOkLinster() {
//            @Override
//            public void onSuccess(Call call, Exception e, int id) {
//                LogKit.E("  Exception ", "  " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
////                updateData(JSONObject.parseObject(response, ResponsePriceEntity.class));
//            }
//
//        }).POST(url, para);
//    }
//
//    /*** 设置商品ID数组，留着验证库存**/
//    private void setGoodPriceIds(List<OrderCartByResponse.CartListBean> cartList) {
//        goodPriceIds = new ArrayList<>();
//        goodCountMap = new HashMap<>();
//        for (OrderCartByResponse.CartListBean bean : cartList) {
//            goodPriceIds.add(bean.getGoods_price_id());
//            goodCountMap.put(bean.getGoods_price_id() + "", bean.getGoods_count());
//        }
//    }
